var allPro = null;
var allBase = null;
var opinion_type = null;
var where_type = null;
$(function () {
    $.when( getdatadictionary("opinion_type"),
        getdatadictionary("where_type"),
    	$.get(baseURL + 'bss/dpoint/select?pGuid='+ GetUrlParam("guid"), function (r) {
            allPro = r.returnlist;
        }),
        $.get(baseURL + 'bss/apbase/select?ourid=isok', function (r) {
            allBase = r.returnlist;
        }) ,
        getBigtype()


    ).done(
    $("#jqGrid").jqGrid({
        url: baseURL + 'bss/dmaterialold/list?dpGuid='+ GetUrlParam("dpguid")+'&pGuid='+ GetUrlParam("pguid"),
        datatype: "json",
        colModel: [			
			{ label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden:true },
			{hidden:true, label: '所属项目ID', name: 'pGuid', index: 'p_guid', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in allBase) {
                        if (cellvalue == allBase[d].guid) return allBase[d].pBName;
                    }
                }
			},
			{ label: '安装位置', name: 'pPGuid', index: 'p_p_guid', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in allPro) {
                        if (cellvalue == allPro[d].guid) return allPro[d].pPCode;
                    }
                }
			},
            { label: '工作类型', name: 'mBWork', index: 'm_b_work', width: 80 },
			{ hidden:true,label: '关联材料信息库ID', name: 'mMGuid', index: 'm_m_guid', width: 80,hidden:true },
			{hidden:true, label: '材料大类', name: 'mBBigtype', index: 'm_b_bigtype', width: 80 },
			{ label: '材料类型', name: 'mBMidtype', index: 'm_b_midtype', width: 80 },
            { label: '设备标签', name: 'dLabel', index: 'd_label', width: 80 } ,
            { label: '材料名称', name: 'mBName', index: 'm_b_name', width: 80 },
			{ label: '主要参数', name: 'mBParameter', index: 'm_b_parameter', width: 80 }, 			
			{ label: '购置单位', name: 'mBUnit', index: 'm_b_unit', width: 80 }, 			
			{ label: '单重（kg）', name: 'mBWeight', index: 'm_b_weight', width: 80 }, 			
			{ label: '数量', name: 'mBCount', index: 'm_b_count', width: 80 },
            { label: '处置意见', name: 'dROpinion', index: 'd_r_opinion', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in opinion_type) {
                        if (cellvalue == opinion_type[d].dKey) return opinion_type[d].dValue;
                    }
                }
            },
			{ label: '拟拆除日期', name: 'dRRemovedate', index: 'd_r_removedate', width: 80,
                formatter:function(value,options,row){
                    return value!=null?new Date(value).Format('yyyy-MM-dd'):"";}
			},
			{ hidden:true,label: ' 处置去向 数据字典where_type', name: 'dRWhere', index: 'd_r_where', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in where_type) {
                        if (cellvalue == where_type[d].dKey) return where_type[d].dValue;
                    }
                }
			},
			{ hidden:true,label: '购置新材料guid', name: 'mBGuid', index: 'm_b_guid', width: 80 },
			{ hidden:true,label: '数据状态', name: 'mBDatastate', index: 'm_b_datastate', width: 80,hidden:true }


        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    })
	)
});


function getdatadictionary(sss)
{

    $.get(baseURL + "api/bdatadictionary/select?d_code="+sss, function(r){
        if(sss=="opinion_type")
        {
            opinion_type=r.returnlist;
        }
        if(sss=="where_type")
        {
            where_type=r.returnlist;
        }

        vm.opinion_type=opinion_type;
        vm.where_type=where_type;

    });
}

function getBigtype() {
    $.ajax({
        type:"post",
        async:false,
        url:baseURL + "api/bmaterial/getBigtype",
        success:function(data){
            for(var i=0;i<data.bigtype.length;i++){
                var sel = document.getElementById('mBigtype');
                sel.options.add(new Option(""+data.bigtype[i].mBigtype+"",""+data.bigtype[i].mBigtype+""));
            }
        }
    });
}

//  大类被选中后触发事件查询对应大类下的中类
function chooseBigtype() {

    var mt = $("#mBigtype").val();
    var sel = document.getElementById('mMidtype');
    sel.options.length=0;
    if(mt==""){
        mt = bigtype;
    }
    $.ajax({
        type:"post",
        async:false,
        url:baseURL + "api/bmaterial/getMidtype?mBigtype="+mt,
        success:function(data){
            for(var i=0;i<data.midtype.length;i++){
                sel.options.add(new Option(""+data.midtype[i].mMidtype+"",""+data.midtype[i].mMidtype+""));
            }
        }
    });
}

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
        q:{
            qLabel:null,
            qName:null,
            names:null,
            lables:null,
        },
		dMaterialOld: {}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.dMaterialOld = {};
            vm.getDept();
		},
		update: function (event) {
			var guid = getSelectedRow();
			if(guid == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            vm.opinion_type=opinion_type;
            vm.where_type=where_type;
            vm.getInfo(guid)
		},
		saveOrUpdate: function (event) {
			var url = vm.dMaterialOld.guid == null ? "bss/dmaterialold/save" : "bss/dmaterialold/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.dMaterialOld),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
        getDept: function () {

            $("#jqGrid1").jqGrid({
                url: baseURL + 'api/bmaterial/list' ,
                datatype: "json",
                colModel: [
                    {label: 'guid', name: 'guid', index: 'guid', width: 50, key: true, hidden: true},

                    {label: '物质编码', name: 'mCode', index: 'm_code', width: 80},
                    {label: '材料中类', name: 'mMidtype', index: 'm_midtype', width: 80},
                    {label: '材料标签', name: 'mLabel', index: 'm_label', width: 80},
                    {label: '材料名称', name: 'mName', index: 'm_name', width: 80},
                    {label: '技术参数', name: 'mParameter', index: 'm_parameter', width: 80},
                    {label: '购置单位', name: 'mUnit', index: 'm_unit', width: 80},
                    {label: '购置单价', name: 'mPrice', index: 'm_price', width: 80},

                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList: [10, 30, 50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth: '100%',
                multiselect: true,
                pager: "#jqGridPager1",
                jsonReader: {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames: {
                    page: "page",
                    rows: "limit",
                    order: "order"
                },
                gridComplete: function () {
                    //隐藏grid底部滚动条
                    $("#jqGrid1").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
                }
            })

        },
        deptTree: function () {
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择明细",
                area: ['800px', '400px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    console.log(index)
                    var grid = $("#jqGrid1");
                    var rowKey = grid.getGridParam("selrow");
                    if (!rowKey) {
                        alert("请选择一条记录");
                        return;
                    }

                    var guids = grid.getGridParam("selarrrow");
                    console.log(guids)
                    if (guids.length > 1) {
                        alert("只能选择一条记录");
                        return;
                    }
                    $.get(baseURL + "api/bmaterial/info/" + guids[0], function (r) {
                        vm.dMaterialOld = {

                            pGuid:GetUrlParam("pguid"),
                            pPGuid:GetUrlParam("dpguid"),
                            mMGuid:r.bMaterial.guid ,
                            mBBigtype:r.bMaterial.mBigtype,
                            mBMidtype:r.bMaterial.mMidtype,
                            mBName: r.bMaterial.mName,
                            mBParameter:r.bMaterial.mParameter,
                            mBWeight:r.bMaterial.mWeight,
                            mBUnit:r.bMaterial.mUnit,

                            //节假日修改
                            wiretype:r.bMaterial.wiretype,
                            wirediam:r.bMaterial.wirediam,
                            mbanktype:r.bMaterial.mbanktype,

                            mBCount:1,
                            dLabel:r.bMaterial.mLabel,
                            mBDatastate:"新增",
                            mBWork:"拆除"
                        // //处置意见  数据字典 opinion_type
                        // private String dROpinion;
                        // //拟拆除日期
                        // private Date dRRemovedate;
                        // // 处置去向 数据字典where_type
                        // private String dRWhere;
                        // //购置新材料guid
                        // private String mBGuid;


                        };
                    });

                    layer.close(index);
                }
            });
        },
        querymy: function () {
            var page = $("#jqGrid1").jqGrid('getGridParam','page');
            $("#jqGrid1").jqGrid('setGridParam',{
                postData: {
                    'mtype': vm.q.mtype,
                    'mName': $("#mname").val(),
                    'mBigtype':$("#mBigtype").val(),
                    'mMidtype':$("#mMidtype").val()

                },
                page:page
            }).trigger("reloadGrid");
        },
        del: function (event) {
			var guids = getSelectedRows();
			if(guids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "bss/dmaterialold/delete",
                    contentType: "application/json",
				    data: JSON.stringify(guids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(guid){
			$.get(baseURL + "bss/dmaterialold/info/"+guid, function(r){
                vm.dMaterialOld = r.dMaterialOld;
                vm.dMaterialOld.dRRemovedate = r.dMaterialOld.dRRemovedate!=null?new Date().Format("yyyy-MM-dd"):"";
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    'qLabel': vm.q.qLabel,
                    'qName': vm.q.qName,

                },
                page:page
            }).trigger("reloadGrid");
		}
	}
});